/**
 * Created by Administrator on 2017/4/18.
 */
/**
 * Created by neal on 11/22/16.
 */
var num = 0;
var CONST_GLOBAL_COMPANY_ID;
var Config = {
    createUrl: '/api/dc/create/company',
    updateUrl: '/api/dc/update/company',
    selectDTUrl: '/api/districts/page'
};

$.validator.setDefaults({
    highlight: function (e) {
        $(e).closest(".form-group").removeClass("has-success").addClass("has-error")
    }, success: function (e) {
        e.closest(".form-group").removeClass("has-error").addClass("has-success");
    }, errorElement: "span", errorPlacement: function (e, r) {
        e.appendTo(r.is(":radio") || r.is(":checkbox") ? r.parent().parent().parent() : r.parent())
    }, errorClass: "help-block m-b-none", validClass: "help-block m-b-none"
});
$("#province").change(function () {
    var id = $(this).val();
    $("input[name=districtId]").val(id);
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            getDistrictByParentId(id, "#city");
            // refreshGrid(data.data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
});
$("#city").change(function () {
    var id = $(this).val();
    $("input[name=districtId]").val(id);
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            getDistrictByParentId(id, "#district");
            // refreshGrid(data.data);
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
});
$("#district").change(function () {
    var id = $(this).val();
    $("input[name=districtId]").val(id);
});
function getDistrictByParentId(id, selectId) {
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var html = [];
            data.data.forEach(function (item) {
                html.push('<option value="' + item.id + '">' + item.name + '</option>');
            });
            $(selectId).html(html.join(''));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}
function getDistrictByParentIdDistrict(id, selectId) {
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var html = [];
            data.data.forEach(function (item) {
                html.push('<option value="' + item.id + '">' + item.name + '</option>');
            });
            $(selectId).html(html.join(''));
            $(".province").val(Number($("input[id=thisProvince]").val()));
            $(".city").val(Number($("input[id=thisCity]").val()));
            $(".district").val(Number($("input[id=thisDistrict]").val()));
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}
function getDistrictByParentIdProvince(id, selectId) {
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var html = [];
            data.data.forEach(function (item) {
                html.push('<option value="' + item.id + '">' + item.name + '</option>');
            });
            $(selectId).html(html.join(''));
            if ($("input[id=thisProvince]").val()) {
                getDistrictByParentIdCity(Number($("input[id=thisProvince]").val()), "#city");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}
function getDistrictByParentIdCity(id, selectId) {
    $.ajax({
        url: Config.selectDTUrl,
        data: {parentid: id, page: 1, rows: 1000},
        type: "GET",
        dataType: "json",
        success: function (data, textStatus, jqXHR) {
            var html = [];
            data.data.forEach(function (item) {
                html.push('<option value="' + item.id + '">' + item.name + '</option>');
            });
            $(selectId).html(html.join(''));
            if ($("input[id=thisCity]").val()) {
                getDistrictByParentIdDistrict(Number($("input[id=thisCity]").val()), "#district");
            }
        },
        error: function (jqXHR, textStatus, errorThrown) {
            toastr.error("网络故障");
        }
    });
}
// $('input:file').localResizeIMG({
//     width: 800,
//     quality: 0.75,
//     success: function (result) {
//         var img = new Image();
//         img.src = result.base64;
//         var formData = new FormData();
//         formData.append('encodedImage', result.base64);
//         formData.append('fileExt', 'jpg');
//         $.ajax({
//             url: '/uploadForCertificate',
//             type: 'POST',
//             data: {encodedImage: result.base64, fileExt: 'jpg'},
//             dataType: 'json',
//             success: function (data) {
//                 if (data.type == "SUCCESS") {
//                     toastr.success(data.msg, data.title);
//                     var id = $(input).attr("id");
//                     if (id == "qrLogoUrlFile") {
//                         $("#qrLogoUrl").val(data.data.imageId);
//                     } else {
//                         alert("系统错误");
//                     }
//                     $(input).siblings("div.update_img").html(img);
//                 } else {
//                     alert("上传失败，请稍后重试");
//                 }
//             }
//         })
//     }
// });
var input;
$("input:file").change(function(){
    input = this;
    lrz(this.files[0], {width: 640})
        .then(function (rst) {
            // 把处理的好的图片给用户看看呗
            var img = new Image();
            img.src = rst.base64;
            img.onload = function () {
                $(".update_img").html(img);
            };
            return rst;
        })
        .then(function (rst) {
            // 这里该上传给后端啦
            // 额外添加参数
            rst.formData.append('fileLen', rst.fileLen);
            $.ajax({
                url: '/uploadForCertificate', // 这个地址做了跨域处理，可以用于实际调试
                data: rst.formData,
                enctype: 'multipart/form-data',
                processData: false,
                contentType: false,
                type: 'POST',
                dataType: 'json',
                success: function (data) {
                    console.log(data+"data");
                    if(data.type=="SUCCESS"){
                        $("#qrLogoUrl").val(data.msg);
                        $(input).parent().siblings("span").html("上传成功");
                        // $(input).parent("div").parent("div").next("div").html('<img src="'+data.msg+'">');
                    }else{
                        alert("上传失败，请稍后重试");
                    }
                }
            });
            return rst;
        })
        .catch(function (err) {
            alert("上传失败，请稍后重试");
        })
        .always(function () {

        });
});

$().ready(function () {
    getDistrictByParentIdProvince(0, "#province");
    $.ajax(
        {
            url: "/api/configs/host/api",
            type: "GET",
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                var qrcode = new QRCode("qrcode", {
                    text: "" + data + "/wap/wx/login?fk=1-17-" + $("input[id=userId]").val() + "-" + $("input[id=companyId]").val() + "",
                    width: 300,
                    height: 300,
                    colorDark: "#0A0A0A",
                    colorLight: "#ffffff",
                    correctLevel: QRCode.CorrectLevel.H
                });
                var QRcode=$("input[id=qrLogoUrl]").val();
                console.log(QRcode);
                if(QRcode&&QRcode!="0"){
                    $.ajax(
                        {
                            url: "/base64",
                            type: "GET",
                            async:false,
                            data:{url:QRcode},
                            success: function (data, textStatus, jqXHR) {
                                console.log(data);
                                var img = new Image();
                                img.src = data;
                                var canvas = document.getElementsByTagName("canvas")[0];
                                var ctx = canvas.getContext('2d');
                                img.onload = function () {
                                    console.log(img);
                                    console.log(canvas);
                                    ctx.save();
                                    ctx.arc(150,150,50,0,Math.PI*2);
                                    ctx.clip();
                                    ctx.drawImage(img, 100, 100, 100, 100);
                                    var dataUrl = canvas.toDataURL();
                                    $("#qrcode img").attr("src", dataUrl);
                                };
                            },
                            error: function (jqXHR, textStatus, errorThrown) {
                                console.log(errorThrown);
                                toastr.error(errorThrown, textStatus);
                            }
                        });
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });

    $('#buttonGoback').click(function () {
        history.go(-1);
        location.reload();
        return false;
    });
});
$('#submitUpdate').click(function () {
    $("#companyForm").validate();
    if ($('#companyForm').valid()) {
        var postData = $('#companyForm').serializeJson();
        postData.province = $('#province option:selected').text();
        postData.city = $('#city option:selected').text();
        if ($('#district option:selected').text() != "" || $('#district option:selected').text() != null) {
            postData.district = $('#district option:selected').text();
        }
        postData.districtId = $("input[name=districtId]").val();
        postData.qrLogoUrl = $("input[name=qrLogoUrl]").val();
        $.ajax({
            url: Config.updateUrl,
            type: "PUT",
            data: postData,
            dataType: "json",
            success: function (data, textStatus, jqXHR) {
                if (data.type === "ERROR") {
                    toastr.success(data.msg, data.title);
                } else {
                    CONST_GLOBAL_COMPANY_ID = data.data.companyId;
                    toastr.success(data.msg, data.title);
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toastr.error(errorThrown, textStatus);
            }
        });
    }

    return false;
});





